using System.Windows;
using System.Windows.Controls;

namespace BiljartHandicap.Navigation
{
    public static class Navigator
    {
        /// <summary>
        /// Gets the value of the attached source property from a dependcy object
        /// </summary>
        /// <param name="obj">The dependency object</param>
        /// <returns>INavigable</returns>
        public static INavigable GetSource(DependencyObject obj)
        {
            return (INavigable)obj.GetValue(SourceProperty);
        }

        /// <summary>
        /// Sets the value of the dependency object
        /// </summary>
        /// <param name="obj">The dependency object</param>
        /// <param name="value">The value for the dependency object (INavigable)</param>
        public static void SetSource(DependencyObject obj, INavigable value)
        {
            obj.SetValue(SourceProperty, value);
        }

        /// <summary>
        /// A dependency property with the name "Source"
        /// Is of the type INavigable and Navigator is the owner
        /// OnSourceChanged is the callback function of the PropertyMetadata
        /// </summary>
        public static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached("Source", typeof(INavigable), typeof(Navigator), new PropertyMetadata(OnSourceChanged));

        /// <summary>
        /// Occurs when the value of the DependencyProperty 'Source' changes
        /// Adds an event to the loaded event of page
        /// </summary>
        /// <param name="dependencyObject">The dependency object</param>
        /// <param name="eventArgs">DependencyPropertyChangedEventArgs</param>
        private static void OnSourceChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
        {
            var page = (Page)dependencyObject;
            page.Loaded += PageLoaded;
        }

        /// <summary>
        /// Gets the INavigable from the given sender (page)
        /// if this is null a new navigationService is instantiated
        /// </summary>
        /// <param name="sender">Page</param>
        /// <param name="e">RoutedEventArgs</param>
        private static void PageLoaded(object sender, RoutedEventArgs e)
        {
            var page = (Page)sender;
            INavigable navSource = GetSource(page);

            if (navSource != null)
            {
                navSource.NavigationService = new NavigationService(page.NavigationService);
            }
        }
    }
}